import React from "react";
import { TextInput, View, TouchableOpacity, ViewStyle } from "react-native";
import { HelperText } from "react-native-paper";
import { Icon } from "@rneui/themed";
import { useTheme } from "@/contexts/ThemeContext";
import styles from "./FormInput.style";

interface FormInputProps {
  value: string;
  onChangeText: (text: string) => void;
  placeholder: string;
  error?: string;
  onBlur?: () => void;
  keyboardType?: "default" | "email-address" | "numeric" | "phone-pad";
  secureTextEntry?: boolean;
  toggleSecureEntry?: () => void;
  autoCapitalize?: "none" | "sentences" | "words" | "characters";
  style?: any;
  containerStyle?: ViewStyle;
}

/**
 * 通用表单输入组件，支持密码显示切换和错误提示
 */
const FormInput: React.FC<FormInputProps> = ({
  value,
  onChangeText,
  placeholder,
  error,
  onBlur,
  keyboardType = "default",
  secureTextEntry = false,
  toggleSecureEntry,
  autoCapitalize = "none",
  style,
  containerStyle,
}) => {
  const { colors } = useTheme();
  const isPasswordInput = toggleSecureEntry !== undefined;

  return (
    <View
      style={[
        error ? styles.containerWithError : styles.container,
        containerStyle,
      ]}
    >
      <TextInput
        style={[
          styles.input,
          {
            borderColor: error ? colors.status.error : colors.border.medium,
            color: colors.text.primary,
            backgroundColor: colors.inputBackground,
            paddingRight: isPasswordInput ? 50 : 16,
          },
          style,
        ]}
        placeholder={placeholder}
        placeholderTextColor={colors.text.hint}
        keyboardType={keyboardType}
        secureTextEntry={secureTextEntry}
        autoCapitalize={autoCapitalize}
        autoCorrect={false}
        value={value}
        onChangeText={onChangeText}
        onBlur={onBlur}
      />

      {isPasswordInput && (
        <TouchableOpacity
          style={styles.iconContainer}
          onPress={toggleSecureEntry}
        >
          <Icon
            name={secureTextEntry ? "visibility" : "visibility-off"}
            type="material"
            size={20}
            color={colors.text.secondary}
          />
        </TouchableOpacity>
      )}

      {error && (
        <HelperText
          style={[styles.errorText, { color: colors.status.error }]}
          type="error"
          visible={!!error}
        >
          {error}
        </HelperText>
      )}
    </View>
  );
};

export default FormInput;
